<?php

class ThemesController extends ThemesAppController
{
	var $name = 'Themes';
	//var $components = array('Session');
	var $helpers = array('Html','Form', 'Javascript', 'Time');
	var $uses = array('Themes.ThemeConfig','Themes.Theme');
	
	function admin_index()
	{	
		$this->pageTitle = __('Themes');	
		$themeFolders = new Folder(APP.DS.'webroot'.DS.'themed');
		$themes = $themeFolders->read(true, array('.svn'));
		$this->set('themes', $themes);	
			
	}
	
	function admin_savetheme($themeName = null)
	{		
		if($themeName && $this->referer()!='/')
		{			
			$themeConfigData['ThemeConfig']['name'] = $themeName;
			$this->ThemeConfig->save($themeConfigData,array('validate'=>false));
			$this->successMsg(sprintf(__('%s theme selected!'),$themeName));
		}
		else
		{
			$this->errorMsg(__('Theme could not be selected.'));
		}
		$this->redirect('/admin/themes');
	}
	
	function admin_add()
	{	
		$this->pageTitle = __('Add Theme');
		if(!empty($this->data))
		{
			$uploadedThemeName = $this->data['Theme']['themeFile']['name'];
			$source = $this->data['Theme']['themeFile']['tmp_name'];
			$type = $this->data['Theme']['themeFile']['type'];
			if($uploadedThemeName == '')
			{
				$this->errorMsg(__('Please select a file.'));
				$this->redirect('/admin/themes/add');
			}
			
			$explodedThemeName = explode('.', $uploadedThemeName);
			//$mainThemeName = Inflector::slug($explodedThemeName[0]);
			$mainThemeName = $explodedThemeName[0];
						
			$pathToSaveFile = APP.'webroot'.DS.'uploadedThemes';  
			$isZipFile = strtolower($explodedThemeName[1]) == 'zip' ? true : false;
			if($isZipFile == false)
			{
				$this->errorMsg(__('Upload a valid zip file!'));
				$this->redirect('/admin/themes/add');
			}
			else
			{				
				if(!file_exists($pathToSaveFile))
				{		
					mkdir($pathToSaveFile);
				}
				//echo $source.'  source path<BR>';
				$destination = $pathToSaveFile.DS.$mainThemeName.'.zip';
				//echo $destination.'  destination path<BR>';
				if(move_uploaded_file($source, $destination))
				{
					// CODE FOR ZIP TO UNZIP FUNCTIONALITY STARTS HERE.
					//uncomment these lines when ZipArchive() is active.
					$zip = new ZipArchive();
					$x = $zip->open($destination);
					if($x === true)
					{						
						$zip->extractTo($pathToSaveFile);
						$zip->close();
						unlink($destination);
					}
					// CODE FOR ZIP TO UNZIP FUNCTIONALITY ENDS HERE

					if($this->copyStuff($mainThemeName) == true)
					{
						$this->successMsg(__('Theme uploaded successfully!'));
						$this->redirect('/admin/themes');
					}
					else
					{
						$this->errorMsg(__('Error in copy operation!'));
					}
					
				}
				else
				{
					$this->errorMsg(__('Theme could not be uploaded.'));
				}
			}					
		}
	}


	function copyStuff($mainThemeName)
	{
		$folderObject = new Folder();
		// copy folder to app/webroot/themed/THEMENAME
		$webrootFolderPath = APP.'webroot'.DS.'themed'.DS.$mainThemeName;
		$folderObject->copy(array(
						'from' => APP.'webroot'.DS.'uploadedThemes'.DS.$mainThemeName.DS.'webroot',
						'to' => $webrootFolderPath
					));

		// copy folder to app/views/themed/THEMENAME
		$viewFolderPath = APP.'views'.DS.'themed'.DS.$mainThemeName;
		$folderObject->copy(array(
						'from' => APP.'webroot'.DS.'uploadedThemes'.DS.$mainThemeName.DS.'views',
						'to' => $viewFolderPath
					));

		// copy preveiw img to app/webroot/themed/PREIVEIW IMAGE
		$source = APP.'webroot'.DS.'uploadedThemes'.DS.$mainThemeName.DS.'preview.jpg';
		$destination = APP.'webroot'.DS.'themed'.DS.$mainThemeName.DS.$mainThemeName.'_preview.jpg';
		
		if(!is_dir(APP.'webroot'.DS.'themed'.DS.$mainThemeName))
		{
			$this->__showError('Unable to copy folders');
		} 
		if(!file_exists($source))
		{
			$this->__showError('Preview image does not exist in you zip file.','/admin/themes/add');
		}
		copy($source,$destination);
		return true;
		
	}

	function __showError($errorMsg = null,$url = null)
	{
		$this->errorMsg(__($errorMsg));
		if($url == null)
		{
			$url = $this->referer();
		}
		$this->redirect($url);
	}
	
	function admin_delete($themeName = null)
	{
		
		if($this->referer()== '/')
		{			
			$this->__showError('Theme could not be delete.','/admin/themes');
		}
		
		$pathToTheme = APP.'webroot'.DS.'themed'.DS.$themeName;
		$selectedTheme = cr('ThemeConfig.name');
		if(is_dir($pathToTheme))
		{
			if($themeName == $selectedTheme)
			{
				$themeConfigData['ThemeConfig']['name'] = '';
				$this->ThemeConfig->save($themeConfigData,array('validate'=>false));
			}
			//removing theme preview image first to prevent error in case of .svn.
			if(is_dir(APP.'webroot'.DS.'themed'.DS.$themeName.DS.'.svn'))
			{
				unlink(APP.'webroot'.DS.'themed'.DS.$themeName.DS.$themeName.'_preview.jpg');
			}else
			{
				$folderObj = new Folder($pathToTheme);
				$folderObj->delete($pathToTheme);
			}
			$this->successMsg(sprintf(__('%s theme deleted successfully!.'),$themeName));
		}
		else
		{
			$this->errorMsg(__('Invalid theme to delete.'));
		}		
		$this->redirect('/admin/themes');
	}
	
}

?>